package com.ruibang.glass.sale.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.Constants;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceCreate;
import com.ruibang.glass.common.domain.camunda.BpmProcessInstanceStatus;
import com.ruibang.glass.common.domain.camunda.BpmTaskApproveReq;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.common.utils.ApproveUserNameUtils;
import com.ruibang.glass.sale.constant.SaleErrorCode;
import com.ruibang.glass.sale.domain.req.GSaleContractManReq;
import com.ruibang.glass.sale.dto.GSaleContractManagementDTO;
import com.ruibang.glass.sale.entity.*;
import com.ruibang.glass.sale.feign.CamundaApi;
import com.ruibang.glass.sale.feign.FileApi;
import com.ruibang.glass.sale.mapper.*;
import com.ruibang.glass.sale.service.CommonService;
import com.ruibang.glass.sale.service.GSaleContractManagementService;
import com.ruibang.glass.sale.service.SerialContractNumberGenerator;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Slf4j
@Service
public class GSaleContractManagementServiceImpl extends ServiceImpl<GSaleContractManagementMapper, GSaleContractManagement> implements GSaleContractManagementService {

    @Autowired
    private GSaleContractProductMapper gSaleContractProductMapper;

    @Autowired
    private GSaleContractFileMapper gSaleContractFileMapper;

    @Autowired
    private FileApi fileApi;

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private CommonService commonService;

    @Autowired
    private CamundaApi camundaApi;

    @Autowired
    private RedisSingleService rediservice;

    @Autowired
    private GSaleOrderMapper saleOrderMapper;

    private static final String SALE_CONTRACT_ZBHT_FILE = "sale_contract_zbht_file";//增补合同
    private static final String SALE_CONTRACT_HTFJ_FILE = "sale_contract_htfj_file";//合同附件

    @Override
    public IPage<GSaleContractManagement> getPage(GSaleContractManReq gSaleContractManReq) {

        LambdaQueryWrapper<GSaleContractManagement> queryWrapper = Wrappers.<GSaleContractManagement>lambdaQuery();
        if (StringUtils.isNotBlank(gSaleContractManReq.getContractName())) {
            queryWrapper.like(GSaleContractManagement::getContractName, gSaleContractManReq.getContractName());
        }
        if (StringUtils.isNotBlank(gSaleContractManReq.getContractNumber())) {
            queryWrapper.like(GSaleContractManagement::getContractNumber, gSaleContractManReq.getContractNumber());
        }
        if (StringUtils.isNotBlank(gSaleContractManReq.getApproveStatus())) {
            queryWrapper.eq(GSaleContractManagement::getApproveStatus, gSaleContractManReq.getApproveStatus());
        }
        if (StringUtils.isNotBlank(gSaleContractManReq.getType())) {
            queryWrapper.eq(GSaleContractManagement::getContractType, gSaleContractManReq.getType());
        }
        Page<GSaleContractManagement> saleContractManagementPage = baseMapper.selectPage(new Page<>(gSaleContractManReq.getPageNo(), gSaleContractManReq.getPageSize()),
                queryWrapper.orderByDesc(GSaleContractManagement::getCreateTime).orderByDesc(GSaleContractManagement::getContractNumber)
        );

        if (CollectionUtils.isEmpty(saleContractManagementPage.getRecords())) {
            return saleContractManagementPage;
        }

        Map<Object, Object> userMap = rediservice.hmget(RedisKey.USER_GROUP_TYPE);
        List<String> businessKeys = saleContractManagementPage.getRecords().stream().map(GSaleContractManagement::getId).collect(Collectors.toList());
        Map<String, BpmProcessInstanceStatus> processMap = null;
        //获取业务流程状态
        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
            processMap = resultBody.getData().stream().collect(Collectors.toMap(bp -> bp.getBusinessKey(), bp -> bp, (bp1, bp2) -> bp1));
        }

        if (processMap != null) {
            for (GSaleContractManagement qualityContact : saleContractManagementPage.getRecords()) {
                if (qualityContact.getOrderQuantity() != null && qualityContact.getDelivered() != null ) {
                    if (qualityContact.getOrderQuantity().compareTo(BigDecimal.ZERO)>0){
                        BigDecimal divide = qualityContact.getDelivered().divide(qualityContact.getOrderQuantity(), 2, RoundingMode.HALF_UP);
                        qualityContact.setCompletionRate(divide.toString());
                    }
                }
                if (userMap.get(qualityContact.getSalesperson()) != null) {
                    qualityContact.setSalesperson(userMap.get(qualityContact.getSalesperson()).toString());
                }
                if (processMap.get(qualityContact.getId()) != null) {
                    qualityContact.setStatus(String.valueOf(processMap.get(qualityContact.getId()).getStatus()));
                    qualityContact.setProcessId(processMap.get(qualityContact.getId()).getProcessInstanceId());
                    if (StringUtils.equals(qualityContact.getApproveStatus(),Constants.TWO_STR)) {
                        if (qualityContact.getStartDate() == null || qualityContact.getEndDate() == null) {
                            qualityContact.setContractStatus(Constants.FOUR_STR);
                        } else {
                            if (qualityContact.getStartDate().isBefore(LocalDateTime.now()) && qualityContact.getEndDate().isAfter(LocalDateTime.now())) {
                                qualityContact.setContractStatus(Constants.ONE_STR);
                            } else {
                                if (qualityContact.getOverDate() != null) {
                                    if (qualityContact.getOverDate().isBefore(LocalDateTime.now())) {
                                        qualityContact.setContractStatus(Constants.THREE_STR);
                                    } else {
                                        qualityContact.setContractStatus(Constants.TWO_STR);
                                    }
                                } else {
                                    qualityContact.setContractStatus(Constants.THREE_STR);
                                }
                            }
                        }
                    } else {
                        qualityContact.setContractStatus(Constants.FOUR_STR);
                    }
//                    qualityContact.setApproveStatus(processMap.get(qualityContact.getId()).getResult());
                    qualityContact.setNodeName(processMap.get(qualityContact.getId()).getNodeName());
                    String userId = processMap.get(qualityContact.getId()).getUserId();
                    if (StringUtils.isNotEmpty(userId) && !StringUtils.equals(userId, "null")) {
                        String approveName = ApproveUserNameUtils.getApproveName(userId, userMap);
                        qualityContact.setApproveUserId(userId);
                        qualityContact.setApproveUser(approveName);
                    }
                }else {
                    if (StringUtils.equals(qualityContact.getApproveStatus(),Constants.TWO_STR)) {
                        if (qualityContact.getStartDate() == null || qualityContact.getEndDate() == null) {
                            qualityContact.setContractStatus(Constants.FOUR_STR);
                        } else {
                            if (qualityContact.getStartDate().isBefore(LocalDateTime.now()) && qualityContact.getEndDate().isAfter(LocalDateTime.now())) {
                                qualityContact.setContractStatus(Constants.ONE_STR);
                            } else {
                                if (qualityContact.getOverDate() != null) {
                                    if (qualityContact.getOverDate().isBefore(LocalDateTime.now())) {
                                        qualityContact.setContractStatus(Constants.THREE_STR);
                                    } else {
                                        qualityContact.setContractStatus(Constants.TWO_STR);
                                    }
                                } else {
                                    qualityContact.setContractStatus(Constants.THREE_STR);
                                }
                            }
                        }
                    } else {
                        qualityContact.setContractStatus(Constants.FOUR_STR);
                    }
                }
            }
        }
        return saleContractManagementPage;
    }

    @Override
    public void approveProject(BpmProcessInstanceCreate bpmProcessInstanceCreate) {
        GSaleContractManagement gSaleContractManagement = baseMapper.selectById(bpmProcessInstanceCreate.getBusinessKey());
        if (gSaleContractManagement != null) {
            baseMapper.updateById(gSaleContractManagement);
        }
        GSaleOrderManagement saleOrderManagement = saleOrderMapper.selectById(bpmProcessInstanceCreate.getBusinessKey());
        if (saleOrderManagement != null) {
            saleOrderMapper.updateById(saleOrderManagement);
        }
        Map<String, Object> variables = new HashMap<>();
        String userId = commonService.getUser().getUserId();
        variables.put(Constants.PROCESS_INSTANCE_STARTER_USER_ID, userId);
        variables.put(Constants.PROCESS_INSTANCE_BUSINESS_KEY, bpmProcessInstanceCreate.getBusinessKey());
        variables.put(Constants.PROCESS_INSTANCE_MENU_ID, bpmProcessInstanceCreate.getMenuId());
        bpmProcessInstanceCreate.setVariables(variables);
        String processId = commonService.startProcess(bpmProcessInstanceCreate);
        if (StringUtils.isNotBlank(processId)) {
            BpmTaskApproveReq bpmTaskApproveReq = new BpmTaskApproveReq();
            bpmTaskApproveReq.setId(processId);
            bpmTaskApproveReq.setUserId(userId);
            camundaApi.approve(bpmTaskApproveReq);
        }
    }


    @Override
    public void addGSaleContractManagement(GSaleContractManagement gSaleCustomerManagement) {
        gSaleCustomerManagement.setApprovalStatus(Constants.ONE_STR);
        gSaleCustomerManagement.setContractNumber(gSaleCustomerManagement.getNumber());
        baseMapper.insert(gSaleCustomerManagement);
        BigDecimal countTotal = BigDecimal.ZERO;
        if (CollectionUtils.isNotEmpty(gSaleCustomerManagement.getGSaleContractProductList())) {
            List<GSaleContractProduct> gSaleContractProductList = gSaleCustomerManagement.getGSaleContractProductList();
            for (GSaleContractProduct gSaleContractProduct : gSaleContractProductList) {
                if (!gSaleCustomerManagement.getContractType().equals(Constants.ONE_STR)) {
                    if (gSaleContractProduct.getQuantity() == null) {
                        throw new ServiceException(SaleErrorCode.SALE_CONTRACT_NO_QUALITY.getCode(), SaleErrorCode.SALE_CONTRACT_NO_QUALITY.getMsg());
                    }
                    countTotal = countTotal.add(gSaleContractProduct.getQuantity());
                }
                gSaleContractProduct.setContractId(gSaleCustomerManagement.getId());
            }
            gSaleContractProductMapper.insertBatch(gSaleContractProductList);
        }
        if (!gSaleCustomerManagement.getContractType().equals(Constants.ONE_STR)) {
            gSaleCustomerManagement.setOrderQuantity(countTotal);
        }
        if (CollectionUtils.isNotEmpty(gSaleCustomerManagement.getFileList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setAttribute(SALE_CONTRACT_HTFJ_FILE);
            fileBusiness.setFileIds(gSaleCustomerManagement.getFileList());
            fileBusiness.setBusinessId(gSaleCustomerManagement.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
        BpmProcessInstanceCreate instanceCreate = new BpmProcessInstanceCreate();
        instanceCreate.setBusinessKey(gSaleCustomerManagement.getId());
        instanceCreate.setMenuId(gSaleCustomerManagement.getMenuId());


        //发起流程
        if (StringUtils.isNotBlank(gSaleCustomerManagement.getCreateUserId())) {
            Map<String, Object> variables = new HashMap<>();
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_STARTER_USER_ID, gSaleCustomerManagement.getCreateUserId());
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_BUSINESS_KEY, gSaleCustomerManagement.getId());
            variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_MENU_ID, gSaleCustomerManagement.getMenuId());
            instanceCreate.setVariables(variables);
        }
        commonService.startProcess(instanceCreate);
        if (gSaleCustomerManagement.getContractType().equals(Constants.TWO_STR) || gSaleCustomerManagement.getContractType().equals(Constants.THREE_STR)) {
            gSaleCustomerManagement.setDelivered(BigDecimal.ZERO);
            gSaleCustomerManagement.setPendingDelivery(gSaleCustomerManagement.getOrderQuantity());
        } else {
            gSaleCustomerManagement.setDelivered(BigDecimal.ZERO);
            gSaleCustomerManagement.setPendingDelivery(BigDecimal.ZERO);
        }
        gSaleCustomerManagement.setApproveStatus(Constants.ZERO_STR);
        baseMapper.updateById(gSaleCustomerManagement);


//        //销售新增 跳过当前人
//        String processId = commonService.startProcess(instanceCreate);
//        //直接通过第一流程节点
//        if (StringUtils.isNotBlank(processId)) {
//            BpmTaskApproveReq bpmTaskApproveReq = new BpmTaskApproveReq();
//            bpmTaskApproveReq.setId(processId);
//            bpmTaskApproveReq.setUserId(commonService.getUser().getUserId());
//            camundaApi.approve(bpmTaskApproveReq);
//        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAddGSaleContractManagement() {
        List<GSaleContractManagement> gSaleContractProducts = baseMapper.selectList();
        for (GSaleContractManagement saleContractProduct : gSaleContractProducts) {
            BpmProcessInstanceCreate instanceCreate = new BpmProcessInstanceCreate();
            instanceCreate.setBusinessKey(saleContractProduct.getId());
            instanceCreate.setMenuId("e0235deec6a011a6f2b5840cea000010");
            saleContractProduct.setCreateUserId("022df7e665d826cf1270f08e81cff25d");
            //发起流程
            if (StringUtils.isNotBlank(saleContractProduct.getCreateUserId())) {
                Map<String, Object> variables = new HashMap<>();
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_STARTER_USER_ID, saleContractProduct.getCreateUserId());
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_BUSINESS_KEY, saleContractProduct.getId());
                variables.put(com.ruibang.glass.common.constants.Constants.PROCESS_INSTANCE_MENU_ID, saleContractProduct.getMenuId());
                instanceCreate.setVariables(variables);
            }
            commonService.startProcess(instanceCreate);

            //获取审批状态
            Map<String, BpmProcessInstanceStatus> processMap = null;
            //获取业务流程状态
            ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(Arrays.asList(saleContractProduct.getId()));
            if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
                processMap = resultBody.getData().stream().collect(Collectors.toMap(bp -> bp.getBusinessKey(), bp -> bp, (bp1, bp2) -> bp1));
            }
            if (processMap != null) {
                saleContractProduct.setApproveStatus(processMap.get(saleContractProduct.getId()).getResult());
            }
            baseMapper.updateById(saleContractProduct);
        }


//        //销售新增 跳过当前人
//        String processId = commonService.startProcess(instanceCreate);
//        //直接通过第一流程节点
//        if (StringUtils.isNotBlank(processId)) {
//            BpmTaskApproveReq bpmTaskApproveReq = new BpmTaskApproveReq();
//            bpmTaskApproveReq.setId(processId);
//            bpmTaskApproveReq.setUserId(commonService.getUser().getUserId());
//            camundaApi.approve(bpmTaskApproveReq);
//        }

    }

    @Override
    public void updateGSaleContractManagement(GSaleContractManagement gSaleCustomerManagement) {
        GSaleContractManagement gSaleContractManagement = baseMapper.selectById(gSaleCustomerManagement.getId());
        gSaleCustomerManagement.setCreateUserId(gSaleContractManagement.getCreateUserId());
        gSaleContractProductMapper.delete(Wrappers.<GSaleContractProduct>lambdaQuery().eq(GSaleContractProduct::getContractId, gSaleCustomerManagement.getId()));
        if (CollectionUtils.isNotEmpty(gSaleCustomerManagement.getGSaleContractProductList())) {
            List<GSaleContractProduct> gSaleContractProductList = gSaleCustomerManagement.getGSaleContractProductList();
            BigDecimal countTotal = BigDecimal.ZERO;
            for (GSaleContractProduct gSaleContractProduct : gSaleContractProductList) {
                if (!gSaleCustomerManagement.getContractType().equals(Constants.ONE_STR)) {
                    if (gSaleContractProduct.getQuantity() == null) {
                        throw new ServiceException(SaleErrorCode.SALE_CONTRACT_NO_QUALITY.getCode(), SaleErrorCode.SALE_CONTRACT_NO_QUALITY.getMsg());
                    }
                    countTotal = countTotal.add(gSaleContractProduct.getQuantity());
                }
                gSaleContractProduct.setContractId(gSaleCustomerManagement.getId());
            }
            for (GSaleContractProduct saleContractProduct:gSaleContractProductList){
                saleContractProduct.setId("");
                gSaleContractProductMapper.insert(saleContractProduct);
            }
            gSaleCustomerManagement.setOrderQuantity(countTotal);
            gSaleCustomerManagement.setDelivered(BigDecimal.ZERO);
            gSaleCustomerManagement.setPendingDelivery(countTotal);
        }

        FileBusiness fileBusiness1 = new FileBusiness();
        fileBusiness1.setBusinessId(gSaleCustomerManagement.getId());
        fileBusiness1.setAttribute(SALE_CONTRACT_HTFJ_FILE);
        fileApi.deleteByBusinessIdAndAttribute(fileBusiness1);
        if (CollectionUtils.isNotEmpty(gSaleCustomerManagement.getFileList())) {
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(gSaleCustomerManagement.getFileList());
            fileBusiness.setBusinessId(gSaleCustomerManagement.getId());
            fileBusiness.setAttribute(SALE_CONTRACT_HTFJ_FILE);
            fileApi.updateBusinessById(fileBusiness);
        }
        baseMapper.updateById(gSaleCustomerManagement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDelayGSaleContractManagement(GSaleContractManagement gSaleCustomerManagement) {
        FileBusiness fileBusiness = new FileBusiness();
        fileBusiness.setBusinessId(gSaleCustomerManagement.getId());
        fileBusiness.setAttribute(SALE_CONTRACT_ZBHT_FILE);
        fileApi.deleteByBusinessIdAndAttribute(fileBusiness);
        if (CollectionUtils.isNotEmpty(gSaleCustomerManagement.getZbFileList())) {
            FileBusiness fileBusiness1 = new FileBusiness();
            fileBusiness1.setAttribute(SALE_CONTRACT_ZBHT_FILE);
            fileBusiness1.setFileIds(gSaleCustomerManagement.getZbFileList());
            fileBusiness1.setBusinessId(gSaleCustomerManagement.getId());
            fileApi.updateBusinessById(fileBusiness);
        }
        GSaleContractManagement gSaleContractManagement = baseMapper.selectById(gSaleCustomerManagement.getId());
        gSaleContractManagement.setEndDate(gSaleCustomerManagement.getOverDate());
        gSaleContractManagement.setOverDate(gSaleCustomerManagement.getOverDate());
        gSaleContractManagement.setOverRemark(gSaleCustomerManagement.getOverRemark());
        baseMapper.updateById(gSaleContractManagement);
    }

    @Override
    public GSaleContractManagement getGSaleContractManagementById(String id) {
        GSaleContractManagement gSaleContractProduct = baseMapper.selectById(id);
        List<GSaleContractProduct> gSaleContractProducts = gSaleContractProductMapper.selectList(Wrappers.<GSaleContractProduct>lambdaQuery().eq(GSaleContractProduct::getContractId, id));
        gSaleContractProduct.setGSaleContractProductList(gSaleContractProducts);
        ResultBody<List<FileBusiness>> fileBusinessesRs = fileApi.getFileBusinessByIds(Arrays.asList(id));
        if (fileBusinessesRs != null && CollectionUtils.isNotEmpty(fileBusinessesRs.getData())) {
            Map<String, FileBusiness> fileBusinessMap = fileBusinessesRs.getData().stream()
                    .collect(Collectors.toMap(
                            fb -> fb.getBusinessId().concat(""), // 键为businessId和attribute的拼接
                            fb -> fb, // 值为FileBusiness对象本身
                            (f1, f2) -> f1 // 如果有冲突，保留第一个FileBusiness对象
                    ));

            FileBusiness fileBusiness = fileBusinessMap.get(gSaleContractProduct.getId().concat(SALE_CONTRACT_HTFJ_FILE));
            if (fileBusiness != null) {
                gSaleContractProduct.setFileList(fileBusiness.getFileIds());
            }
            fileBusiness = fileBusinessMap.get(gSaleContractProduct.getId().concat(SALE_CONTRACT_ZBHT_FILE));
            if (fileBusiness != null) {
                gSaleContractProduct.setZbFileList(fileBusiness.getFileIds());
            }

        }
        return gSaleContractProduct;
    }

    @Override
    public List<GSaleContractManagement> getGSaleContractManagementList() {
        List<GSaleContractManagement> gSaleContractManagements = baseMapper.selectList();
        List<String> businessKeys = gSaleContractManagements.stream().map(GSaleContractManagement::getId).collect(Collectors.toList());
//        ResultBody<List<BpmProcessInstanceStatus>> resultBody = camundaApi.queryProcessInstanceStatus(businessKeys);
//        //获取审批状态
//        Map<String, BpmProcessInstanceStatus> processMap = null;
//        if (resultBody != null && CollectionUtils.isNotEmpty(resultBody.getData())) {
//            processMap = resultBody.getData().stream().collect(Collectors.toMap(bp -> bp.getBusinessKey(), bp -> bp, (bp1, bp2) -> bp1));
//        }
        Map<String, String> idsMap = new HashMap<>();
        for (GSaleContractManagement saleContractManagement : gSaleContractManagements) {
            if (StringUtils.equals(saleContractManagement.getApproveStatus(), Constants.TWO_STR)) {
                idsMap.put(saleContractManagement.getId(), saleContractManagement.getId());
            }
        }
        //老数据跳过流程验证
        for (GSaleContractManagement gSaleContractManagement : gSaleContractManagements) {
            if (StringUtils.equals(gSaleContractManagement.getOldStatus(), Constants.TWO_STR)) {
                idsMap.put(gSaleContractManagement.getId(), gSaleContractManagement.getId());
            }
        }
        List<GSaleContractManagement> saleContractManagements = new ArrayList<>();
        List<GSaleContractManagement> gSaleContractManagements1 = baseMapper.getGSaleContractManagementList();
        if (idsMap != null) {
            for (GSaleContractManagement saleContractManagement : gSaleContractManagements1) {
                if (StringUtils.isNotBlank(idsMap.get(saleContractManagement.getId()))) {
                    saleContractManagements.add(saleContractManagement);
                }
            }
        }
        return saleContractManagements;
    }

    @Override
    public IPage<GSaleContractManagementDTO> getNewPage(GSaleContractManReq gSaleContractManReq) {
        IPage<GSaleContractManagementDTO> newPage = baseMapper.getNewPage(new Page<>(gSaleContractManReq.getPageNo(), gSaleContractManReq.getPageSize()), gSaleContractManReq);
        if (newPage.getRecords() != null) {
            Map<Object, Object> userMap = rediservice.hmget(RedisKey.USER_GROUP_TYPE);
            for (GSaleContractManagementDTO saleContractManagementDTO : newPage.getRecords()) {
                if (StringUtils.isNotBlank(saleContractManagementDTO.getSalesperson())) {
                    if (userMap.get(saleContractManagementDTO.getSalesperson()) != null) {
                        saleContractManagementDTO.setSalesperson(userMap.get(saleContractManagementDTO.getSalesperson()).toString());
                    }
                }
                if (StringUtils.isNotBlank(saleContractManagementDTO.getCreateUserId())) {
                    if (userMap.get(saleContractManagementDTO.getCreateUserId()) != null) {
                        saleContractManagementDTO.setCreateUserName(userMap.get(saleContractManagementDTO.getCreateUserId()).toString());
                    }
                }
            }
        }
        return newPage;
    }

    @Override
    public void export(GSaleContractManReq gSaleContractManReq, HttpServletResponse response) {
        String fileName = "销售合同报表" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss") + ".xlsx";
        try {
            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");

            // 设置响应内容类型和字符编码
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");

            // 设置Content-Disposition头部，告诉浏览器这是一个文件下载请求
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

            // 获取导出数据
            IPage<GSaleContractManagementDTO> checkList = baseMapper.getNewPage(new Page<GSaleContractManagementDTO>(0L, 2000L), gSaleContractManReq);
            List<GSaleContractManagementDTO> list = checkList.getRecords();

            // 使用EasyExcel写入数据到响应输出流
            EasyExcel.write(response.getOutputStream(), GSaleContractManagementDTO.class).excelType(ExcelTypeEnum.XLSX).sheet("销售合同报表").doWrite(list);

            // 刷新输出流
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如设置错误状态码或错误消息
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出Excel时发生错误");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }


    @Override
    public List<GSaleContractProduct> getContractsProductList(String id) {
        List<GSaleContractProduct> gPurchaseContractProductsList = gSaleContractProductMapper
                .selectList(Wrappers.<GSaleContractProduct>lambdaQuery()
                        .select(GSaleContractProduct::getProductId, GSaleContractProduct::getProductName, GSaleContractProduct::getMaterialCode,
                                GSaleContractProduct::getExecutionStandards,
                                GSaleContractProduct::getUnit)
                        .eq(GSaleContractProduct::getContractId, id));
        return gPurchaseContractProductsList;
    }


    @Override
    public String generateNextSerialNumber() {
        GSaleContractManagement gSaleContractManagement = baseMapper.selectOne(Wrappers.<GSaleContractManagement>lambdaQuery().isNotNull(GSaleContractManagement::getContractNumber)
                .like(GSaleContractManagement::getContractNumber, "PA")
                .orderByDesc(GSaleContractManagement::getContractNumber).last("limit 1"));
        if (gSaleContractManagement == null) {
            String s = SerialContractNumberGenerator.generateNextSerialNumber(null);
            return s;
        }
        String s = SerialContractNumberGenerator.generateNextSerialNumber(gSaleContractManagement.getContractNumber());
        return s;
    }

}
